#coding:utf-8
#Author Robin Wang Li xin
#Email:Luobintianya@gmail.com
#copyright: datiandou.com
from django.http import HttpRequest
from django.http import HttpResponse
from django.template import Context, loader, RequestContext
from django.template.loader import get_template
from django.shortcuts import render, get_object_or_404, render_to_response, HttpResponseRedirect
from django import http
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from datiandouweb.models import DUploadFile,UserProfile,CommReg,Resume,Language,Status,Message
from datiandouweb.forms import  FileUploadCvForm
import json
from django.core.files.uploadedfile import UploadedFile
from datiandou import settings
import uuid
import logging
import os
from django.db import transaction
from django.http import HttpResponse, HttpResponseBadRequest
logger = logging.getLogger(__name__)
from django.db.models import Q
from django.core.servers.basehttp import FileWrapper
import mimetypes
import traceback
from django.utils import timezone
from django.contrib.auth.models import User, GroupManager,Group
import json
from datetime import datetime,timedelta
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from datiandouweb import fwsutils
##############################approval cv############################



@csrf_exempt
def load_approval_cv(request):
    userId=request.session.get("userID")
    status=request.POST.get('status')
    print(status)
    ap_st=Status.objects.filter(Status_type=1)
    if status is not None and status !='':
        resumes=Resume.objects.select_related('Language_id','File_id','Resume_status').filter(Resume_status__Status_key=status,Resume_status__Status_type=1)
    elif status =='':
        resumes=Resume.objects.select_related('Language_id','File_id','Resume_status').filter(Q(Resume_status__Status_type=1))
    else:
        resumes=Resume.objects.select_related('Language_id','File_id','Resume_status').filter(Q(Resume_status__Status_key=1)|Q(Resume_status__Status_key=2),Q(Resume_status__Status_type=1))
    #状态类型为简历状态
    print(resumes)
    return fwsutils.fws_response('cvcenter/approvalcv.html',request,{'resumes':resumes,"sts":ap_st,"status":status})


@csrf_exempt
def update_approval_cv(request):
    userId= request.session.get("userID")
    rrids= request.POST.get("rids")
    type= request.POST.get("type")
    print(type)
    rids = str(rrids[0:-1]).split(",") if rrids is not None else ''
    print(rids)
    msg=""
    issuccess=False;
    for rid in rids:
        try:
            resume=Resume.objects.select_related('Language_id','File_id','Resume_status').get(Q(Resume_status__Status_type=1),Q(Resume_id=rid), Q(Resume_status__Status_key=1)|Q(Resume_status__Status_key=2),                                                                                              Q(Resume_id=rid))#状态类型为简历状态
            if resume is not None:
                    if type is not None and type =="passed":
                        msg="您的<b>"+str(resume.Resume_name).encode('utf-8')+"</b>简历已审核通过!欢迎您的加入,成为大田斗一员."
                        re_st = Status.objects.get(Status_type=1,Status_key=3)
                    elif type is not None and type =="notpassed":
                        msg="您的<b>"+str(resume.Resume_name).encode('utf-8')+"</b>简历无法通过审核,请重新上传简历."
                        re_st = Status.objects.get(Status_type=1,Status_key=4)
                    resume.Resume_status = re_st
                    resume.save()
                    from_id= UserProfile.objects.get(pk=1)
                    to_id= UserProfile.objects.get(pk=userId)
                    ms_st=Status.objects.get(Status_type=4,Status_key =2) #4 消息类型 2已读消息
                    ms=Message.objects.create(From_id =from_id,To_id=to_id,Message_type=0,Message_content =msg,Send_Date_Time = datetime.now(),status =ms_st )
                    msg="审核操作成功！";
                    ms.save()
                    transaction.commit()
                    issuccess=True
        except Resume.DoesNotExist: ##已经审批通过的无法再次更改审批状态
                msg="审核操作失败"
                issuccess=False
                transaction.rollback()
        except Exception as e:
                logging.error(e)
                issuccess=False
                msg="审核操作失败,请找土拨鼠"
                transaction.rollback()

    print(rids)
    jvalue = json.dumps({"msg":msg,"is_success":issuccess});
    if request.is_ajax():
        print("ajax")
    return fwsutils.fws_ajax_response(jvalue, mimetype="application/json")


#############################cv center ###################################
@csrf_exempt
def load_cv(request):
    userId=request.session.get("userID")
    resumes=Resume.objects.select_related('Language_id','File_id','Resume_status').filter(user_id=userId, Resume_status__Status_type=1)#状态类型为简历状态
    old = (datetime.now() - timedelta(days=10))
    messages=Message.objects.filter(To_id=userId,Message_type=0,Send_Date_Time__gt=old.strftime("%Y-%m-%d")).order_by('-Send_Date_Time')
    print(messages)
    return fwsutils.fws_response('cvcenter/cvcenter.html',request,{'resumes':resumes,'ms':messages})


@csrf_exempt
@transaction.autocommit
def del_cv(request,resume_id):
    userId = request.session.get("userID")
    resume= Resume.objects.select_related('File_id').get(Resume_id = resume_id,user_id=userId)
    try:
        resume.File_id.Status=3 #文件将被删除
        resume.File_id.save()
        resume.delete()
    except:
        print("error happend!")

    return fwsutils.fws_redirect_response('../load',request)


@csrf_exempt
@transaction.autocommit
def refresh_cv(request):
    userId = request.session.get("userID")
    resumes= Resume.objects.select_related('Language_id','File_id','Resume_status').filter(user_id=userId, Resume_status__Status_type=3)##only update 审核通过
    try:
        for resume in resumes:
            resume.Update_time = datetime.time()
            resume.save()
    except:
        logger.error("error when update_cv_statue!")
    return fwsutils.fws_redirect_response('load',request)



@csrf_exempt
def download_file(request,resume_id):
    userId = request.session.get("userID")
    user = User.objects.get(id = userId)
    resume = None
    isroot = False
    for group in user.groups.all():
        if group.name == 'ROOT':
            isroot=True
            try:
                resume=Resume.objects.select_related('File_id').get(Q(Resume_id = resume_id),Q(File_id__Status=1)|Q(File_id__Status=2),Q(File_id__Type=1))
                if resume is not None and resume.Resume_status.Status_key < 2 and resume.Resume_status.Status_type==1:
                    resume.Resume_status = Status.objects.get(Status_type=1,Status_key =2) # 状态为已读 2 为已读 1类型为简历
                    resume.save(force_update=True,update_fields=['Resume_status'])
                    msg="SYSTEM已阅读了您的<b>"+str(resume.Resume_name).encode('utf-8')+"</b>简历".encode('utf-8')
                    from_id= UserProfile.objects.get(pk=1)
                    to_id= UserProfile.objects.get(pk=userId)
                    ms_st=Status.objects.get(Status_type=4,Status_key =2) #4 消息类型 2已读消息
                    ms=Message.objects.create(From_id =from_id,To_id=to_id,Message_type=0,Message_content =msg,Send_Date_Time = datetime.now(),status =ms_st )
                    ms.save()
                    transaction.commit()
                    break
            except Exception as e:
                #print(e)
                logging.error(e)
                transaction.rollback()

    if not isroot:
        resume=Resume.objects.select_related('File_id').get(Q(Resume_id = resume_id),Q(user_id=userId),Q(File_id__Status=1)|Q(File_id__Status=2),Q(File_id__Type=1))
    if resume is not None:
        file_path = unicode(str(resume.File_id.File_path),'utf8')
        file_name = resume.File_id.File_name.encode('utf-8')
        print(file_path)
        # statobj = os.stat((file_path))
        wrapper = FileWrapper(open(file_path,'rb'))
        content_type = mimetypes.guess_type(resume.File_id.File_name)[0]
        if(content_type is None):
            content_type="application/msword"
        print(content_type)
        print(file_name)
        response = HttpResponse(wrapper,mimetype=content_type)
        response['Pragma']= "public"
        response['Content-Transfer-Encoding']= "binary"
        response['Content-Length']= os.path.getsize(file_path)
        response['Content-Disposition'] = 'attachment; filename=%s;' % str(file_name)
        response['X-Sendfile'] = file_name
        return response
    else:
        return fwsutils.fws_redirect_response('../load',request)




##加载上传弹窗口
@csrf_exempt
def load_upload_cv(request):
    ## 此处的语言id 必须和language 表语言id相同
    userId=request.session.get("userID")
    language=CommReg.objects.filter(Type='selectbox',Status='0',schema='cv_language',User_id='system')
    return fwsutils.fws_response('cvcenter/uploadcv.html', request,{'language': language})






@transaction.autocommit
@csrf_exempt
def save_upload(request):
    if request.method =='POST':
        form = FileUploadCvForm(request.POST) # A form bound to the POST data
        userId=request.session.get("userID")
        userInfo = UserProfile.objects.get(User_id=userId)
        if form.is_valid(): # All validation rules pass
            print("ok")
            cv_name=form.cleaned_data['cv_name'].strip();
            cv_language=form.cleaned_data['cv_language'].strip();
            file_id=form.cleaned_data['filename'].strip();
            status=form.cleaned_data['is_open']
            file = DUploadFile.objects.get(File_id=file_id)
            file.Status = '2' # 文件状态等于2意味着正在使用中
            language= Language.objects.get(Language_id=cv_language)
            cv=Resume()
            cv.File_id=file
            cv.Resume_name=cv_name
            cv.user_id=userInfo
            cv.Language_id=language
            cv.Resume_status = Status.objects.get(Status_type=1,Status_id=1001) # 初始状态等待审核
            cv.Resume_type=status;
            try:
                cv.save()
                file.save()
            except:
                print("保存文件出错！")
            print(form.data['cv_name'])

    return fwsutils.fws_redirect_response('load',request)

#废弃因为IE8
def response_mimetype(request):
    if "application/json" in request.META['HTTP_ACCEPT']:
        return "application/json"
    else:
        return "text/plain"

@csrf_exempt
def multi_uploader(request):
    userId=request.session.get("userID")
    userInfo = UserProfile.objects.get(User_id=userId)
    result = []
    if request.method == 'POST':
        try:
            if request.FILES == None:
                return HttpResponseBadRequest('Must have files attached!')
            file = request.FILES[u'files[]']
            wrapped_file = UploadedFile(file)
            filename = wrapped_file.name
            file_size = wrapped_file.file.size
            print('Got file: "%s"' % str(filename.encode('utf-8')))
            try:
                file_part=str(timezone.datetime.today().strftime("%Y_%m_%d"))+'/'+ str(uuid.uuid4())
                file_url_path = settings.FILE_UPLOAD_ROOT+"storeCV/"+file_part
            except AttributeError:
                file_url_path = settings.FILE_UPLOAD_ROOT+'/storeCV/'
                #settings imports
            if(not os.path.exists(file_url_path)):
                os.makedirs(file_url_path)
            filefullpaht=file_url_path+'/'+filename
            # open the file handler with write binary mode
            print("文件路径"+file_url_path)
            destination = open(filefullpaht, "wb+")
            for chunk in file.chunks():
                destination.write(chunk)
                # close the file
            destination.close()
            storeFile=DUploadFile()
            storeFile.File_path=filefullpaht
            storeFile.User_id=userInfo
            storeFile.Type='1' # 简历
            storeFile.Status='1' #正常
            storeFile.File_name= filename
            storeFile.Create_time = timezone.now()
            storeFile.save()
            #generating json response array

            result.append({"name":filename.split(".")[0],
                           "size":file_size,
                           "url":file_url_path,
                           "key":storeFile.pk,
                           "error":''})
            response_data = json.dumps(result)
            print("上传结束");
        except Exception, e:
            result.append({"name":filename.split(".")[0],
                           "size":file_size,
                           "url":file_url_path,
                           "key":storeFile.pk,
                           "error":'上传失败'})
            response_data = json.dumps(result)
            print("上传失败")
            print(traceback.print_exc())
            print(e.args)
        return fwsutils.fws_ajax_response(response_data,mimetype="text/plain")

    else: #GET
        return fwsutils.fws_ajax_response('不支持GET 上传！',mimetype="application/json")
